package com.lwj.file.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.lwj.file.entity.OrderDTO;
import com.lwj.file.mapper.OrderDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class DemoDataListener implements ReadListener<OrderDTO> {

    private static final int BATCH_COUNT = 1000;

    private ThreadLocal<ArrayList<OrderDTO>> cachedDataList = ThreadLocal.withInitial(ArrayList::new);

    private OrderDao orderDao;

    public DemoDataListener(OrderDao demoDAO) {
        this.orderDao = demoDAO;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(OrderDTO data, AnalysisContext context) {
        cachedDataList.get().add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.get().size() >= BATCH_COUNT) {
            asyncSaveData();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
    }

    public void asyncSaveData() {
        if (!cachedDataList.get().isEmpty()) {
            ArrayList<OrderDTO> cachedData = (ArrayList<OrderDTO>) cachedDataList.get().clone();
           //此处最好使用mq处理，如果使用CompletableFuture需要传入自定义线程池
            CompletableFuture.runAsync(()->{
                saveData(cachedData);
            });
            cachedDataList.get().clear();
        }
    }
    /**
     * 存储数据库
     */
    private void saveData(List<OrderDTO> cachedDataList) {
            log.info("{}条数据，开始存储数据库！", cachedDataList.size());
            orderDao.batchSave(cachedDataList);
    }


}
